package com.wakala.employment.fragment.login;

import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.android.tu.loadingdialog.LoadingDailog;
import com.hjq.toast.Toaster;
import com.wakala.employment.R;
import com.wakala.employment.activity.MainActivity;
import com.wakala.employment.adapter.entity.LoginInfo;
import com.wakala.employment.adapter.entity.User;
import com.wakala.employment.core.BaseFragment;
import com.wakala.employment.core.http.subscriber.NoTipRequestSubscriber;
import com.wakala.employment.databinding.FragmentLoginPwdBinding;
import com.wakala.employment.fragment.other.LoginFragment;
import com.wakala.employment.http.TestApi;
import com.wakala.employment.utils.SettingUtils;
import com.wakala.employment.utils.TokenUtils;
import com.wakala.employment.utils.Utils;
import com.wakala.employment.utils.sdkinit.UMengInit;
import com.xuexiang.xhttp2.XHttpProxy;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.enums.CoreAnim;
import com.xuexiang.xui.utils.ResUtils;
import com.xuexiang.xui.utils.ThemeUtils;
import com.xuexiang.xui.utils.ViewUtils;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xutil.app.ActivityUtils;
import com.xuexiang.xutil.tip.ToastUtils;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link LoginPwdFragment#} factory method to
 * create an instance of this fragment.
 */
@Page(anim = CoreAnim.none)
public class LoginPwdFragment extends BaseFragment<FragmentLoginPwdBinding> implements View.OnClickListener {


    //private View mJumpView;
    private CheckBox cbProtocol;

    @NonNull
    @Override
    protected FragmentLoginPwdBinding viewBindingInflate(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, boolean attachToRoot) {
        return FragmentLoginPwdBinding.inflate(inflater, container, attachToRoot);
    }

    @Override
    protected TitleBar initTitle() {
        TitleBar titleBar = super.initTitle()
                .setImmersive(true);
        titleBar.setBackgroundColor(Color.TRANSPARENT);
        titleBar.setTitle("");
        titleBar.setLeftImageDrawable(ResUtils.getVectorDrawable(getContext(), R.drawable.ic_login_close));
        titleBar.setActionTextColor(ThemeUtils.resolveColor(getContext(), R.attr.colorAccent));
        return titleBar;
    }

    @Override
    protected void initListeners() {
        super.initListeners();
        binding.tvOtherLogin.setOnClickListener(this);
        binding.btnLogin.setOnClickListener(this);
        binding.tvUserProtocol.setOnClickListener(this);
        binding.tvPrivacyProtocol.setOnClickListener(this);
    }

    @Override
    protected void initArgs() {
        super.initArgs();
    }

    @Override
    protected void initViews() {
        //隐私政策弹窗
        if (!SettingUtils.isAgreePrivacy()) {
            Utils.showPrivacyDialog(getContext(), (dialog, which) -> {
                dialog.dismiss();
                handleSubmitPrivacy();
            });
        }
        cbProtocol = binding.cbProtocol;
        //初始化必须为默认不勾选
        binding.cbProtocol.setChecked(false);
        boolean isAgreePrivacy = SettingUtils.isAgreePrivacy() && cbProtocol.isChecked();
        refreshButton(isAgreePrivacy);
        binding.cbProtocol.setOnCheckedChangeListener((buttonView, isChecked) -> {
            SettingUtils.setIsAgreePrivacy(isChecked);
            refreshButton(isChecked);
        });
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id){
            case R.id.tv_other_login:
                openPage(LoginFragment.class);
                break;
            case R.id.btn_login:
                if (binding.etPhoneNumber.validate()) {
                    if (binding.etPassword.validate()) {
                        loginByPassword(binding.etPhoneNumber.getEditValue(), binding.etPassword.getEditValue());
                    }
                }
                break;
            case R.id.tv_user_protocol:
                Utils.gotoProtocol(this, false, true);
                break;
            case R.id.tv_privacy_protocol:
                Utils.gotoProtocol(this, true, true);
                break;
            default:
                Toaster.show("没有次操作");
        }
    }

    private void refreshButton(boolean isChecked) {
        ViewUtils.setEnabled(binding.btnLogin, isChecked);
        //ViewUtils.setEnabled(mJumpView, isChecked);
    }

    private void handleSubmitPrivacy() {
        SettingUtils.setIsAgreePrivacy(true);
        UMengInit.init();
        // 应用市场不让默认勾选
        ViewUtils.setChecked(cbProtocol, true);
    }

    private void loginByPassword(String phoneNumber, String password) {
        LoadingDailog.Builder loadBuilder=new LoadingDailog.Builder(getContext())
                .setMessage("登录中...")
                .setCancelable(true)
                .setCancelOutside(true);
        LoadingDailog dialog=loadBuilder.create();
        dialog.show();
        //使用XHttpProxy进行接口代理请求
        XHttpProxy.proxy(TestApi.IAuthorization.class)
                .login(phoneNumber, password)
                .subscribeWith(new NoTipRequestSubscriber<LoginInfo>() {
                    @Override
                    public void onSuccess(LoginInfo loginInfo) {
                        dialog.dismiss();
                        //ToastUtils.toast("图书购买" + (aBoolean ? "成功" : "失败") + "！");
                        //mRefreshLayout.autoRefresh();
                        onLoginSuccess(loginInfo);
                    }
                    @Override
                    public void onError(ApiException e) {
                        dialog.dismiss();
                        super.onError(e);
                        ToastUtils.toast(e.getDisplayMessage());
                    }
                });

    }

    /**
     * 登录成功的处理
     */
    private void onLoginSuccess(LoginInfo loginInfo) {
        //String token = RandomUtils.getRandomNumbersAndLetters(16);
        if (TokenUtils.handleLoginSuccess(loginInfo)) {
            getLoginUserInfo();
            //popToBack();
            //ActivityUtils.startActivity(MainActivity.class);
        }
    }

    /**
     * 根据token获取当前登录用户信息
     */
    private void getLoginUserInfo(){
        LoadingDailog.Builder loadBuilder=new LoadingDailog.Builder(getContext())
                .setMessage("加载数据中...")
                .setCancelable(true)
                .setCancelOutside(true);
        LoadingDailog dialog=loadBuilder.create();
        dialog.show();
        XHttpProxy.proxy(TestApi.IUserService.class)
                .getLoginUserInfo()
                .subscribeWith(new NoTipRequestSubscriber<User>() {
                    @Override
                    public void onSuccess(User user) {
                        dialog.dismiss();
                        TokenUtils.setmLoginUser(user);
                        popToBack();
                        ActivityUtils.startActivity(MainActivity.class);
                    }
                    @Override
                    public void onError(ApiException e) {
                        dialog.dismiss();
                        super.onError(e);
                        ToastUtils.toast(e.getDisplayMessage());
                    }
                });
    }
}